package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: fd
 * @Date 2021/5/11 14:50
 * @Description:集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

	/**
	 * 参数校验异常捕获
	 * @author fd
	 * @date 2021/5/11 15:19
	 * @param exception
	 * @return com.atguigu.common.utils.R
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public R handleValidException(MethodArgumentNotValidException exception){

		Map<String,String> map = new HashMap<>(1,0.75f);
		// 获取数据校验的错误结果
		BindingResult bindingResult = exception.getBindingResult();
		// 处理错误
		bindingResult.getFieldErrors().forEach(fieldError -> {
			map.put(fieldError.getField(),fieldError.getDefaultMessage());
		});

		log.error("数据校验出现问题{},异常类型{}",exception.getMessage(),exception.getClass());

		return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data",map);
	}

	/**
	 * 捕获的异常范围更大
	 * @author fd
	 * @date 2021/5/11 15:19
	 * @param throwable
	 * @return com.atguigu.common.utils.R
	 */
	@ExceptionHandler(value = Throwable.class)
	public R handleException(Throwable throwable){
		log.error("未知异常{},异常类型{}",
				throwable.getMessage(),
				throwable.getClass());
		return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),
				BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
	}


}
